// 自定义国际化配置
import { createI18n, Locale } from 'vue-i18n';
import { VxeUI } from '@/plugins/vxe';
import zhCN from 'vxe-pc-ui/lib/language/zh-CN';
import enUS from 'vxe-pc-ui/lib/language/en-US';
import zhTW from 'vxe-pc-ui/lib/language/zh-TW';
// import viVN from 'vxe-pc-ui/lib/language/vi-VN';
// import viVN from 'vxe-table/lib/language/vi-VN'

// en_US km_KH vi_VN zh_CN zh_TW
VxeUI.setI18n('en_US' as any, enUS);
VxeUI.setI18n('zh_CN' as any, zhCN);
VxeUI.setI18n('zh_TW' as any, zhTW);

// VxeUI.setI18n('km_KH' as any, enUS);
// VxeUI.setI18n('vi_VN' as any, viVN);

// 本地语言包
const modules = import.meta.glob('./**/*.yaml');
const messages: any = {};
for (const [modulePath, module] of Object.entries(modules)) {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [_, lang, ns] = modulePath.match(/\/(.*?)\/(.*?)\./) as any[];
  if (!messages[lang]) {
    messages[lang] = {};
  }
  messages[lang][ns] = module;
}
// console.log(messages);

export const languages = Object.keys(messages);

/**
 * 获取当前语言
 * @returns zh-cn|en ...
 */
export const getLanguage = () => {
  const language = useStorage('language', 'zh_CN');
  if (language.value) {
    return language.value;
  }
  return 'zh_CN';
};

const i18n = createI18n({
  legacy: false,
  locale: '',
  messages: {}
});

function setI18nLanguage(locale: Locale) {
  i18n.global.locale.value = locale;
}

const loadedLanguages = new Set<string>();

export async function loadI18nMessages(lang: Locale) {
  if (unref(i18n.global.locale) === lang) {
    return setI18nLanguage(lang);
  }
  if (loadedLanguages.has(lang)) {
    return setI18nLanguage(lang);
  }
  const message: any = {};
  for (const ns of Object.keys(messages[lang])) {
    const module = messages[lang][ns];
    message[ns] = (await module()).default;
  }

  // 兼容 lang 不在 翻译语言当中，默认切换为 en_US
  if (!Object.keys(message.language).includes(lang)) {
    lang = 'en_US';
  }

  i18n.global.setLocaleMessage(lang, message);
  loadedLanguages.add(lang);

  VxeUI.setLanguage(lang as any);
  return setI18nLanguage(lang);
}

export default i18n;
export const t = i18n.global.t;

// 旧版语言映射
export const LANG_MAP = {
  zh_TW: 'zh-TW',
  zh_CN: 'zh-CN',
  vi_VN: 'vi',
  my_MM: 'my',
  id_ID: 'id',
  km_KH: 'km',
  en_US: 'en'
};
